package com.hlyj.http.base.tool.lib_hlyj_base.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.PixelFormat
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import com.cszy.mfjx.lib_hlyj_base.R

import java.lang.ref.WeakReference

@SuppressLint("StaticFieldLeak")
object OverlayViewUtils {
    private var customView: WeakReference<View>? = null
    private var windowManager: WeakReference<WindowManager>? = null
    /**
     * 显示自定义悬浮窗
     */
    @SuppressLint("SuspiciousIndentation")
    fun showCustomOverlay(activity: Activity, info: String) {
        if (activity.isFinishing || activity.isDestroyed) {
            Log.e("qin", "Activity is finishing or view already exists")
            return
        }  // 先移除已有悬浮窗
        removeCustomOverlay()
        // 初始化 WindowManager
        val windowManager = activity.getSystemService(WindowManager::class.java)
        this.windowManager = WeakReference(windowManager)

        // 加载自定义布局
        val inflater = activity.getSystemService(LayoutInflater::class.java)
        val customView = inflater.inflate(R.layout.custom_bottom_view, null)
        this.customView = WeakReference(customView)
        TextView(activity).apply {
            customView?.findViewById<TextView>(R.id.customText)?.text = info
        }

        // 设置布局参数
        val layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_PANEL, // 类型
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, // 不获取焦点
            PixelFormat.TRANSLUCENT // 透明背景
        ).apply {
            gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
            x = 0 // 水平偏移量
            y = 150 // 垂直偏移量
        }

        // 将视图添加到 WindowManager
        windowManager?.addView(customView, layoutParams)
    }

    /**
     * 判断当前 Activity 是否属于目标包
     */
    fun isTargetPackageActivity(activity: Activity): Boolean {
        val targetPackage = "com.cysd.ewmxns.ui.activity"
        // 1. 检查是否属于目标包
        if (activity::class.java.name.startsWith(targetPackage)) {
            return true
        }
        // 2. 检查是否是 HtmlActivity（包含 WebView）
        return activity::class.java.simpleName == "HtmlActivity"
    }

    /**
     * 移除自定义悬浮窗
     */
    fun removeCustomOverlay() {
        val windowManager = windowManager?.get()
        val customView = customView?.get()
        if (customView != null && windowManager != null) {
            try {
                windowManager.removeView(customView)
            } catch (e: Exception) {
                Log.e("OverlayUtils", "Failed to remove custom view: ${e.message}")
            }
        }
        this.customView = null
        this.windowManager = null
    }
}